import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaDialog, WeaTab, WeaTools, WeaLocaleProvider } from 'ecCom';
import { Button, Spin, Menu, Dropdown, Icon } from 'antd';
import RemindListStore from '../../stores/remindStore/RemindListStore';
import AddRemindForm from './AddRemindForm';
import RemindListItem from './RemindListItem';
import moment from 'moment';
import './../../style/index';
import './../../util/index';
import ViewContactLogItem from '../public/ViewContactLogItem';

const getLabel = WeaLocaleProvider.getLabel;
const getLocaleLabel = WeaLocaleProvider.getLocaleLabel.bind(this, 'crm');
const { getLocaleLabelByCode } = WeaLocaleProvider;
@observer
export default class RemindList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: '',
      startValue: new Date().setDate(1),
      endValue: new Date(),
      store: new RemindListStore(),
    };
  }
  index = 0;
  componentWillMount() {
    getLocaleLabelByCode('crm').then(() => {
      const { store } = this.state;
      const { doNew } = store;
      doNew(this);
    });
  }
  componentDidMount() {
    const dom = document.getElementById('container');
    this.setState({ layout: dom });

    const ua = window.navigator.userAgent;
    if (ua.match('E-Mobile')) { // 如果在EMPC

    } else if (!ua.match('E-Mobile') && window.em) { // 如果在EM网页

    } else if (parent.document.getElementsByClassName('wea-messageCenter-leftList').length > 0) {
      const head1 = parent.document.getElementsByClassName('wea-messageCenter-leftList')[0];
      head1.style.padding = '0 0 12px 0';
    }
    // getLocaleLabelByCode('crm').then(() => this.setState({ reRender: true }));
    // console.log(66666666);
    // console.log(window.weaCrm);
    // if (window.weaCrm) {
    //     this.setState({ weaCrmLoaded: true});
    // } else {
    //     eventRegister.loadModule('f_crm', () => {
    //         this.setState({ weaCrmLoaded: true});
    //     }, () => {
    //         alert("加载客户模块失败，请联系系统管理员！");
    //     });
    // }
  }
  componentWillUnmount() {
    const ua = window.navigator.userAgent;
    if (ua.match('E-Mobile')) { // 如果在EMPC

    } else if (!ua.match('E-Mobile') && window.em) { // 如果在EM网页

    } else if (parent.document.getElementsByClassName('wea-messageCenter-leftList').length > 0) {
      const head1 = parent.document.getElementsByClassName('wea-messageCenter-leftList')[0];
      head1.style.padding = '0 0 12px 12px';
    }
  }
  render() {
    const { store, visible, layout, visible1, contactlog = {}, title, scrollid, crmid, weaCrmLoaded } = this.state;
    const { params, reminds, tabkey, changTabKey, inIt, loading, isSuccess, changeContent, deleteRemindByRole } = store;

    const topTab = [
      {
        title: getLabel('332', '全部'),
        viewcondition: 'all',
      },
      {
        title: getLabel('84239', '系统提醒'),
        viewcondition: 'system',
      },
      {
        title: getLabel('127015', '我发出的'),
        viewcondition: 'mySend',
      },
      {
        title: getLabel('514777', '我收到的'),
        viewcondition: 'myReceive',
      },
    ];

    const buttons = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5ml8sd@sure`} type="primary" onClick={() => {
        this.refs.remindFormRef.state.store.saveAddRemind();
      }}>{getLabel('826', '确定')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4e5e0u@reset`} type="primary" onClick={() => {
        this.refs.remindFormRef.state.store.resetForm();
      }}>{getLabel('2022', '重置')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@hp79pl@cancel`} type="ghost" onClick={() => {
        this.onDiaClose();
      }}>{getLabel('201', '取消')}</Button>,
    ];
    const listWeaDialog = [];
    let listWeaTab = [];
    const ua = window.navigator.userAgent;
    const menu = (
      <Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@k93wim`}>
        <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@yl8mf8`}>
          <a target="_blank" href={'javaScript:window.open(\'/wui/index.html#/main/crm/mineCustomer\')'}>{getLabel('388635', '客户列表')}</a>
        </Menu.Item>
        <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@f5rms1`}>
          <a target="_blank" href={'javaScript:window.open(\'/wui/index.html#/main/crm/sellChance\')'}>{getLabel('514779', '商机列表')}</a>
        </Menu.Item>
      </Menu>
    );
    listWeaTab.buttons = [];
    // listWeaTab.buttons.push(<Dropdown overlay={menu}>
    //     <Button type="primary" >
    //         更多
    //     </Button>
    // </Dropdown>);
    if (ua.match('E-Mobile')) { // 如果在EMPC
      listWeaTab = [];
    } else if (!ua.match('E-Mobile') && window.em) { // 如果在EM网页
      listWeaTab.buttons.push([<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@kso4d7@create`} type="primary" onClick={() => {
        this.setState({ visible: true });
      }}>{getLabel('82', '新建')}</Button>]);
      listWeaDialog.zIndex = 100001;
    } else {
      listWeaTab.buttons.push([<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@89h0fr@create`} type="primary" onClick={() => {
        this.setState({ visible: true });
      }}>{getLabel('82', '新建')}</Button>]);
    }

    // 如果在EC中
    return (
      <div className="crm-remind-list-pc">
        {/* {weaCrmLoaded&&11111111} */}
        <WeaTab
          ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@ikcbid`}
          datas={topTab}
          keyParam="viewcondition" // 主键
          selectedKey={tabkey}
          onChange={(v) => {
            this.index = 0;
            changeContent('');
            changTabKey(v);
            inIt();
          }}
          searchType={['base']}
          onSearch={(value) => {
            changeContent(value); inIt(); this.index = 0;
          }}
          {...listWeaTab}
        />
        <div className="crm-pc-chance-remind-main">
          {loading ? <div style={{ margin: '50px auto', textAlign: 'center', height: 'auto' }}><Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@2sxfzi`} tip="Loading..." /></div> : this.getRemindList()}
        </div>
        <WeaDialog
          ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@7sk6qe`}
          onCancel={() => this.onDiaClose()}
          title={getLabel('82210', '新建提醒')}
          visible={visible}
          hasScroll
          buttons={buttons}
          icon={'icon-coms-crm'}
          iconBgcolor="#96358a"
          {...listWeaDialog}
          style={{ width: 500, height: 500 }}
        >
          <div style={{ padding: '15px' }}>
            <AddRemindForm
              ecId={`${this && this.props && this.props.ecId || ''}_AddRemindForm@1556gu`}
              ref="remindFormRef"
              params={{}}// 参数
              onDiaCloseClick={this.onDiaClose}
            />
          </div>
        </WeaDialog>
        <WeaDialog
          ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@toav5v`}
          onCancel={() => {
            this.setState({ visible1: false });
          }}
          title={<span>{getLabel('17532', '联系记录')}-<a onClick={() => {
            this.onNameClick(crmid);
          }}>{title}</a></span>}
          visible={visible1}
          hasScroll
          buttons={[<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@i0tc47@close`} type="primary" onClick={() => {
            this.setState({ visible1: false });
          }}>{getLabel('309', '关闭')}</Button>]}
          icon={'icon-coms-crm'}
          iconBgcolor="#96358a"
          {...listWeaDialog}
          style={{ width: 500, height: 400 }}
        >
          <div style={{ display: 'flex', flexDirection: 'column' }} id="crm-contacte-log-dialog">
            <ViewContactLogItem ecId={`${this && this.props && this.props.ecId || ''}_ViewContactLogItem@6yx39h`} item={contactlog} scrollid={scrollid} />
          </div>
        </WeaDialog>
      </div>
    );
  }
  getRemindList = () => {
    const { store } = this.state;
    const { reminds, deleteRemindByRole } = store;
    const remindList = [];
    const today = moment().format('YYYY-MM-DD');
    const yestoday = moment().add('days', -1).format('YYYY-MM-DD');

    reminds.length > 0 && reminds.map((item, i) => {
      // console.log(item);
      const { createdate } = item;
      if (createdate != this.currentData) {
        this.currentData = createdate;
        this.index = 0;
      }
      if (createdate == today) {
        this.tip = getLabel('514760', '今日提醒');
      } else if (createdate == yestoday) {
        this.tip = getLabel('514761', '昨日提醒');
      } else if (createdate == '1900-01-01') {
        this.tip = getLabel('514762', '未提醒');
      } else {
        this.tip = createdate;
      }
      this.index++;
      remindList.push(
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {this.index == 1 &&
            <div className="crm-pc-sellchance-remind-tip" >
              {this.tip}
            </div >}
          <RemindListItem
            ecId={`${this && this.props && this.props.ecId || ''}_RemindListItem@ehjic1@${i}`}
            item={item}
            onOpenContact={(id) => {
              WeaTools.callApi('/api/crm/customer/contactLogs', 'POST', { labelid: 'all', id, datatype: 0 }).then((result) => {
                if (result.status == 'success') {
                  this.setState({ contact: id, visible1: true, contactlog: result.datas.rsList[0], title: result.datas.rsList[0].crmname, crmid: result.datas.rsList[0].crmid });
                }
              });
            }}
            deleteRemindByRole={deleteRemindByRole}
          />
        </div>,
      );
    });
    return remindList;
  }
  onDiaClose = (type) => {
    this.setState({ visible: false });
    const { store } = this.state;
    const { inIt } = store;
    if (type == 1) {
      inIt();
    }
  }
  onNameClick = (crmid) => {
    window.open(`/spa/crm/static/index.html#/main/crm/customerView?customerId=${crmid}`, '_blank');
  }
}
